﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using NewsMine.Utilities;

namespace NewsMine.Storage
{
    public class FolderSyncLocker:IDisposable
    {
        int delayCounterForRecursion = 2;
        string syncFile = null;
        bool isTimedOut = false;
        FileStream s;
        DateTime startTime;
        DateTime endTime;
        public FolderSyncLocker(string folderPath)
        {
            startTime = DateTime.UtcNow;
            syncFile = Path.Combine(folderPath, "syncFile.lck");

            WaitAndOpenSyncFile();
        }

        private void WaitAndOpenSyncFile()
        {
            try
            {
                s = File.OpenWrite(syncFile);
            }
            catch (Exception e)
            {
                if (s == null)
                {
                    if (delayCounterForRecursion < 600)
                    {
                        delayCounterForRecursion = delayCounterForRecursion * 2;
                        Thread.Sleep(10 * delayCounterForRecursion);
                        WaitAndOpenSyncFile();
                    }
                    else
                        isTimedOut = true;

                }
            }
        }

        public void Dispose()
        {
            endTime = DateTime.UtcNow;

            if ((endTime - startTime).TotalMilliseconds > 2000)
                TempLogger.LogCustom("syncLockTracking.txt", (endTime - startTime).TotalMilliseconds.ToString() + " Milliseconds." + "\t"  + syncFile + Environment.NewLine + Environment.StackTrace.ToString());

            if (isTimedOut == true)
            {

                TempLogger.Log("FolderSync timed out for the folder " + Path.GetDirectoryName(syncFile));
            }
            try
            {
                s.Close();
                File.Delete(syncFile);
            }
            catch (Exception e)
            {
                TempLogger.Log("error while deleting syncFile.lck file: " + e.Message + "- " + e.StackTrace);
            }
        }
    }
}
